package net.yegong.gdal;

import java.io.File;
import java.util.Scanner;

import net.yegong.gdal.Gdal.Utility;

public class GdalInfo {

	public GdalInfo(File f) throws Exception {
		String target = String.format("\"%s\"", f.getAbsoluteFile());
		info = Gdal.run(Utility.GDAL_INFO, "-noct", "-nogcp", "-nomd", target);
		parse();
	}

	private void parse() {
		Scanner sc = new Scanner(info);
		while (sc.hasNextLine()) {
			try {
				String line = sc.nextLine();
				if (line.equals("Driver: HFA/Erdas Imagine Images (.img)")) {
					valid = true;
				}
				if (line.startsWith("Size is ")) {
					line = line.replace("Size is ", "");
					String[] array = line.split(", ");
					if (2 == array.length) {
						rows = Integer.parseInt(array[1]);
						cols = Integer.parseInt(array[0]);
					}
				}
				if (line.startsWith("Band ")) {
					line = line.replace("Band ", "");
					String[] array = line.split(" ");
					if (array.length > 1) {
						String bandIndex = array[0];
						bands = Math.max(bands, Integer.parseInt(bandIndex));
					}
				}
			}
			catch (NumberFormatException e) {
				e.printStackTrace();
			}
		}
	}

	public int getBands() {
		return bands;
	}

	public int getRows() {
		return rows;
	}

	public int getCols() {
		return cols;
	}

	public boolean isValid() {
		return valid;
	}

	private int bands;
	private int rows;
	private int cols;
	private boolean valid;
	private final String info;
}
